//
//  XLWhoLookMeVC.m
//  XiangLove
//
//  Created by 李传坤 on 2018/6/12.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLWhoLookMeVC.h"
#import "IMAChatViewController.h"
#import "XLHTTPSessionManager.h"
#import "XLMyFriendTableCell.h"
#import "XLAccountManager.h"
#import <ReactiveCocoa.h>
#import "XLMyFriendModel.h"

#import "XLPersonPageViewController.h"
#import "MJRefresh.h"
#import "BMHPromptView.h"
#import "NSString+Ext.h"

@interface XLWhoLookMeVC ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) UITableView    *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,copy  ) NSString            *page;
@property (nonatomic,strong) XLMyFriendModel   *FriendModel;
@property (nonatomic,strong) UIButton       *charmBtn;
@property (nonatomic, strong) BMHPromptView      *promptView;

@end

@implementation XLWhoLookMeVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = NO;
    [self showBackButton:NULL];
    self.navigationItem.title = @"谁看过我";
    _page = @"1";
    // Do any additional setup after loading the view.
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self addTableView];
    [self requrstTalkedPeoplePage];
    
}
#pragma mark - getter
- (BMHPromptView *)promptView {
    if (_promptView == nil) {
        _promptView = [[BMHPromptView alloc] initWithImage:[UIImage imageNamed:@"pic_nothing_n"]];
        [_promptView.reTryButton setTitle:@"还没有访客记录呢" forState:UIControlStateNormal];
        [self.view addSubview:_promptView];
        [_promptView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(200, 215));
            make.center.equalTo(self.view);
        }];
    }
    return _promptView;
}


-(void)requrstTalkedPeoplePage
{
    NSDictionary *dic = @{@"pageIndex":_page,
                          @"pageSize":@"16",
                          @"userId":[[XLAccountManager shareInstance]model].Id,
                          };
    [[[XLHTTPSessionManager sharedManager]XLV2GET:@"/api/v2/UserInfo/ViewedPersonList" parameters:dic resultClass:[XLMyFriendModel class]] subscribeNext:^(id x) {
        NSLog(@"美女列表==%@",x);
        [MBProgressHUD hideHUDForView:self.view];
        self.tableView.hidden = NO;
        
        NSArray * listAry = x;
        if (![x isKindOfClass:[NSNull class]] && listAry.count > 0) {
            [self getJsonArray:listAry];
            [_promptView removeFromSuperview];
            _promptView = nil;
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }else{
            if ([self.page isEqualToString:@"1"]) {
                self.promptView.hidden = NO;
                self.tableView.hidden = YES;
            }
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    } error:^(NSError *error) {
        NSLog(@"%@", error);
        [MBProgressHUD hideHUDForView:self.view];
        if (self.modelArray.count == 0) {
        }
        if ([self.page isEqualToString:@"1"]) {
            self.promptView.hidden = NO;
            self.tableView.hidden = YES;
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }];
    
}

- (void)getJsonArray:(NSArray *)array {
    if ([array isKindOfClass:[NSNull class]] || array.count == 0 || array == nil) {
        
    } else {
        if ([self.page isEqualToString:@"1"]) {
            [self.modelArray removeAllObjects];
        } else {
            
        }
        [self.modelArray addObjectsFromArray:array];
    }
    [self.tableView reloadData];
}
#pragma mark - 下拉刷新
- (void)handelGCHeaderTableView {
    self.page = @"1";
    [self requrstTalkedPeoplePage];
    //[self reshOnlinePeoplesData];
    
}

#pragma mark - 上拉加载
- (void)handelGCFootTableView {
    self.page = [NSString stringWithFormat:@"%d", [self.page intValue] + 1];
    [self requrstTalkedPeoplePage];
}

- (NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

-(void)addTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, XQScreenW, XQScreenH) style:UITableViewStylePlain];
    _tableView.rowHeight = 86;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    [_tableView registerClass:[XLMyFriendTableCell class] forCellReuseIdentifier:NSStringFromClass([XLMyFriendTableCell class])];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(handelGCHeaderTableView)];
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(handelGCFootTableView)];
    [self.view addSubview:_tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return <#expression#>
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XLMyFriendTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLMyFriendTableCell class]) forIndexPath:indexPath];
    XLMyFriendModel  *model = [self.modelArray objectAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.headerImageView setImageWithURL:[NSURL URLWithString:model.HeadImg] placeholder:[UIImage imageWithColor:RGB(255, 255, 255)]];
    NSString *levelUrl;
    if ([model.IsAnchor integerValue] == 1) {
        levelUrl = [NSString stringWithFormat:@"me_grade_icons_zb0%@",model.UserLevel];
    }else{
        levelUrl = [NSString stringWithFormat:@"me_grade_icons_yh0%@",model.UserLevel];
    }
    if ([model.UserLevel integerValue] > 9) {
        if ([model.IsAnchor integerValue] == 1) {
            levelUrl = [NSString stringWithFormat:@"me_grade_icons_zb%@",model.UserLevel];
        }else{
            levelUrl = [NSString stringWithFormat:@"me_grade_icons_yh%@",model.UserLevel];
        }
    }
    cell.levelImage.image = [UIImage imageNamed:levelUrl];
    cell.nickNameLabel.text = model.NickName;
    if (cell.nickNameLabel.text.length == 0) {
        cell.nickNameLabel.text = @"      ";
    }
    CGFloat width = [cell.nickNameLabel.text sizeWidthsFont:18 andHeight:20];
    width += 70;//加上头像
    cell.ageLabel.frame = CGRectMake(width, 22, 36, 16);
    cell.sexImage.frame = CGRectMake(width + 4, 24, 12, 12);
    cell.levelImage.frame = CGRectMake(width + 40 , 22, 33, 16);
    cell.isFriend.frame = CGRectMake(width + 75 , 22, 33, 16);
    if ([model.IsFriend integerValue] == 1) {
        cell.isFriend.hidden = NO;
    }else{
        cell.isFriend.hidden = YES;
    }
    if ([model.Sex integerValue] == 1) {
        cell.ageLabel.backgroundColor = RGB_HEX(0xFFA6D8);
        cell.sexImage.image = [UIImage imageNamed:@"common_icon_nv_n"];
    }else
    {
        cell.ageLabel.backgroundColor = RGB_HEX(0xB7D0FF);
        cell.sexImage.image = [UIImage imageNamed:@"common_icon_nan_n"];
    }cell.ageLabel.text = model.Age;
    cell.infor.text = model.Intro;
    cell.onlineState.textColor = kLightGrayColor;
    cell.ageLabel.text = [NSString stringWithFormat:@"     %@",model.Age];
    if ([model.OnLineStatus isEqualToString:@"0"]) {
        cell.onlineState.text = @"离线";
        cell.onlineState.textColor = kDarkGrayColor;
        
    }else{
        
        cell.onlineState.text = @"在线";
        cell.onlineState.textColor = kDarkGrayColor;
    }
    
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XLMyFriendModel  *model = [self.modelArray objectAtIndex:indexPath.row];
    NSString *toUserId = model.UserId;
    [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[toUserId] succ:^(NSArray *friends) {
        
        for (TIMUserProfile *pro in friends)
        {
            IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
            dispatch_async(dispatch_get_main_queue(), ^{
                IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                chat.ChatViewBackBlock = ^{
                    UIViewController * presentingViewController = self.presentingViewController;
                    while (presentingViewController.presentingViewController) {
                        presentingViewController = presentingViewController.presentingViewController;
                    }
                    [presentingViewController dismissViewControllerAnimated:NO completion:nil];
                };
                [self.navigationController pushViewController:chat animated:YES];
            });
        }
    } fail:^(int code, NSString *msg) {
        DebugLog(@"vvvFailddd: %d->%@", code, msg);
    }];
    
}












-(void)goChatText:(UIButton *)sender//去主页
{
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"])
    {
        UIButton * chatText = sender;
        self.charmBtn = chatText;
        self.charmBtn.enabled =NO;
        [self performSelector:@selector(changeButtonStatus) withObject:nil afterDelay:0.5f];//防止重复点击
        XLMyFriendModel *model = self.modelArray[chatText.tag];
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[model.UserId] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    //                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            DebugLog(@"vvvFailddd: %d->%@", code, msg);
        }];
        
    }
    
}

-(void)changeButtonStatus{
    self.charmBtn.enabled =YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
